﻿using CanDoo.Admin.Core.Contracts;
using CanDoo.Admin.Core.Identity;
using CanDoo.Core.Context;
using CanDoo.Core.Data;
using CanDoo.Core.Logging;
using CanDoo.Core.Security;
using CanDoo.Data;
using CanDoo.Extensions;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Oil.Core.DTOs;
using CanDoo.Oil.Core.Models;
using CanDoo.Oil.WebApi.Api.Results;
using CanDoo.Oil.WebApi.Areas.Api.Filters;
using Microsoft.Owin.Security;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace CanDoo.Oil.WebHost.Areas.Api.Controllers
{
    [TinderApiExceptionFilterAttribute]
    [TinderValidationActionFilter]
    [Description("媒体上传webapi")]
    [RoutePrefix("api/media")]
    public class MediaController : ApiController
    {
        #region owin

        public IAuthenticationManager AuthenticationManager { get; private set; }//认证管理
        public SignInManager SignInManager { get; private set; }//登陆管理

        #endregion

        #region Manager

        public IPermissionManager PermissionManager { get; private set; }
        public IOperateLoger OperateLoger { get; set; }
        public IOperator Operator { get; set; }

        /// <summary>
        /// 售油机序列号
        /// </summary>
        public IOilSalesSerialNumContract OilSalesSerialNumContract { get; set; }
        public ICustomerContract CustomerContract { get; set; }//客户管理
        public IUserContract UserContract { get; set; }//用户管理

        /// <summary>
        /// Api操作日志
        /// </summary>
        public IAPIOperateLogContract APIOperateLogContract { get; set; }
        public IStoreActivityContract StoreActivityContract { get; set; }

        public IProductContract ProductContract { get; set; }

        /// <summary>
        /// 取油吗
        /// </summary>
        public IGetOilCodeContract GetOilCodeContract { get; set; }

        public IOilSerialNumContract OilSerialNumContract { get; set; }

        public IMediaADContract MediaADContract { get; set; }

        public IConfigContract ConfigContract { get; set; }

        public IMoneyChangeContract MoneyChangeContract { get; set; }

        public IAppUpdateContract AppUpdateContract { get; set; }

        public IOilSiteConfig sysStaticConfig { get; set; }

        public IDB DB { get; set; }

        #endregion

        #region 属性

        private string _PageCode;
        public string PageCode
        {
            get
            {
                if (string.IsNullOrEmpty(_PageCode))
                {
                    _PageCode = this.GetType().Name;
                }
                return _PageCode;
            }
        }

        private string _pageTitle;
        public string PageTitle
        {
            get
            {
                if (string.IsNullOrEmpty(_pageTitle))
                {
                    _pageTitle = this.GetType().ToDescription();
                }
                return _pageTitle;
            }
        }

        #endregion

        #region ctor

        public MediaController(IAuthenticationManager authenticationManager
            , SignInManager signInManager
            , IPermissionManager permissionManager
            )
        {
            AuthenticationManager = authenticationManager;
            SignInManager = signInManager;
            PermissionManager = permissionManager;

            PermissionManager.PageCode = PageCode;
            PermissionManager.PageTitle = PageTitle;
        }

        #endregion

        // GET: api/Media
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Media/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Media
        public async Task<ApiResult> Post(MediaInfo mediaInfo)
        {
            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(functionCode: "PostMedia", pagecode: this.PageCode, powerName: "媒体上传", pageTitle: this.PageTitle, creatNewIfNotExists: true);
            OperateLoger.InputMessage = JsonConvert.SerializeObject(mediaInfo);
            OperateLoger.OperationResult = OperationResult.Success;

            var result = new ApiResult();

            var entity = MediaADContract.FirstOrDefault(p => p.IsDeleted == false && p.MD5 == mediaInfo.md5);
            if(entity != null)
            {
                entity.Name = mediaInfo.name;
                entity.Size = mediaInfo.size;
                entity.Url = mediaInfo.mediaUrl;
                entity.StartTime = DateTime.Parse(mediaInfo.startPlayTime);
                entity.EndTime = DateTime.Parse( mediaInfo.endPlayTime);

                var or = MediaADContract.UpdateEntity(entity);
                if (or.Succeeded == false)
                {
                    result.ResultType = ApiResultType.error;//操作成功信息编号
                    result.Message = or.Message;      //操作成功信息
                    result.InnerMessage = or.Message;      //操作成功信息
                }
                else
                {
                    result.ResultType = ApiResultType.sucess;
                    result.InnerMessage = "操作成功";
                    result.Message = or.Message;
                }
            }
            else
            {
                var mediaAD = new MediaAD();
                mediaAD.Name = mediaInfo.name;
                mediaAD.Size = mediaInfo.size;
                mediaAD.Url = mediaInfo.mediaUrl;
                mediaAD.StartTime = DateTime.Parse(mediaInfo.effectiveTime);
                mediaAD.EndTime = DateTime.Parse(mediaInfo.endPlayTime);
                mediaAD.MD5 = mediaInfo.md5;

                var or = MediaADContract.AddEntity(mediaAD);
                if (or.Succeeded == false)
                {
                    result.ResultType = ApiResultType.error;//操作成功信息编号
                    result.Message = or.Message;      //操作成功信息
                    result.InnerMessage = or.Message;      //操作成功信息
                }
                else
                {
                    result.ResultType = ApiResultType.sucess;
                    result.InnerMessage = "操作成功";
                    result.Message = or.Message;
                }
            }

            OperateLoger.OutputMessage = JsonConvert.SerializeObject(result);
            OperateLoger.OperationResult = result.ResultType == ApiResultType.sucess ? OperationResult.Success : new OperationResult(OperationResultType.Error, result.InnerMessage);
            await OperateLoger.SaveLogAsync();
            return result;
            //return Request.CreateResponse(result.ResultType == ApiResultType.sucess ? HttpStatusCode.OK : HttpStatusCode.OK, result);
        }

        // PUT: api/Media/5
        public void Put(int id, [FromBody]string value)
        {

        }

        // DELETE: api/Media/5
        public void Delete(int id)
        {
        }
    }
}
